package com.mayikt.service.impl;

import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.entity.PaymentChannelEntity;
import com.mayikt.entity.PaymentTransactionEntity;
import com.mayikt.mapper.PaymentChannelMapper;
import com.mayikt.mapper.PaymentTransactionMapper;
import com.mayikt.service.PaymentAggregateService;
import com.mayikt.strategy.PayStrategy;
import com.mayikt.utils.SpringContextUtils;
import com.mayikt.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class PaymentAggregateServiceImpl extends BaseApiService implements PaymentAggregateService {

    @Autowired
    private PaymentChannelMapper paymentChannelMapper;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private PaymentTransactionMapper paymentTransactionMapper;

    @Override
    public BaseResponse<String> toPayHtml(String payToken, String channelId) {
        // 1.验证参数
        if (StringUtils.isEmpty(payToken)) {
            return setResultError("payToken不能为空!");
        }
        if (StringUtils.isEmpty(channelId)) {
            return setResultError("channelId不能为空!");
        }
        // 2.根据渠道id查询到详细渠道的信息
        PaymentChannelEntity pce = paymentChannelMapper.selectBychannelId(channelId);
        if (pce == null) {
            return setResultError("该渠道已关闭或不存在，请联系管理员");
        }

        // 4.根据beanid 从Spring容器中找到策略类执行
        String payBeanId = pce.getPayBeanId();
        if (StringUtils.isEmpty(payBeanId)) {
            return setResultError("没有配置payBeanId");
        }
        // 5.根据payToken查询到支付参数内容
        String tokenValue = tokenUtil.getTokenValue(payToken);
        if (StringUtils.isEmpty(tokenValue)) {
            return setResultError("支付已经超时");
        }
        // 6.获取我们的预支付的参数的信息
        Long payId = Long.parseLong(tokenValue);
        PaymentTransactionEntity ptc = paymentTransactionMapper.selectById(payId);
        if (ptc == null) {
            return setResultError("请不要随意攻击我们支付平台");
        }
        PayStrategy payStrategy = SpringContextUtils.getBean(payBeanId, PayStrategy.class);
        // 7.统一返回html表单给客户端
        String data = payStrategy.toPayHtml(pce, ptc);
        log.info("result:" + data);
        return setResultSuccess(data);
    }
}